package com.qianheng.kit.base.util;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;

@Slf4j
public class ObjUtil {

    public static void tryIgnored(Callable<Object> callable) {
        try {
            callable.call();
        } catch (Exception ignored) {
        }
    }

    public static <O> O tryOrNull(ThrowingSupplier<O> tryDo) {
        try {
            return tryDo.get();
        } catch (Exception e) {
            return null;
        }
    }

    public static <O> O tryOrNull(ThrowingSupplier<O> tryDo, Consumer<Exception> consumer) {
        try {
            return tryDo.get();
        } catch (Exception e) {
            consumer.accept(e);
            return null;
        }
    }

    public static <O> O tryOrElse(ThrowingSupplier<O> tryDo, Function<Exception, O> orElse) {
        try {
            return tryDo.get();
        } catch (Exception e) {
            return orElse.apply(e);
        }
    }

    public static <O> O tryOrDefault(ThrowingSupplier<O> tryDo, O orElse) {
        try {
            return tryDo.get();
        } catch (Exception e) {
            return orElse;
        }
    }

    public static <T> T deepCopy(T source, Class<T> clazz) {

        return JSONUtil.toBean(JSONUtil.toJsonStr(source), clazz);
    }

}
